import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js'
import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js'
import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js'

const gltfLoader = new GLTFLoader()
const dracoLoader = new DRACOLoader()
dracoLoader.setDecoderPath('/js/threejs/jsm/libs/draco/')
// gltfLoader.setDRACOLoader(dracoLoader)
gltfLoader.setMeshoptDecoder(MeshoptDecoder)
const ktx2Loader = new KTX2Loader()
ktx2Loader.setTranscoderPath('/js/threejs/jsm/libs/basis/')
gltfLoader.setKTX2Loader(ktx2Loader)

let lastProgress = 0
/**
 *
 * @param {String} url  模型路径
 * @param {THREE.WebGLRenderer} [renderer] 渲染器, 用于检测ktx2支持
 * @returns
 */
const loadGltf = (url, renderer) =>
  new Promise(resolve => {
    if (renderer) ktx2Loader.detectSupport(renderer)
    gltfLoader.load(
      url,
      gltf => {
        resolve(gltf)
      },
      xhr => {
        const progress = (xhr.loaded / xhr.total) * 100
        if (progress - lastProgress >= 5) {
          console.log(progress + '% loaded')
          lastProgress = progress
        }
        if (progress === 100) {
          console.log('加载完成')
        }
      }
    )
  })

export default loadGltf
